<template>
  <div>
    <van-nav-bar
      fixed
      placeholder
      safe-area-inset-top
      title="经纪人服务"
      @click-left="back"
    >
      <template #left>
        <van-icon name="arrow-left" size="16px" color="#333" />
      </template>
    </van-nav-bar>
    <!-- <div
      v-show="agentReview.checkStatus === 3 || agentReview.checkStatus === 0"
    > -->
    <div>
      <div class="info">
        <span class="haveto">*</span>身份证
        <span>(身份证信息需和从业资格证信息一致)</span>
      </div>
      <div v-show="pass" class="picup">
        <van-uploader
          v-model="fileListid"
          accept="image/*"
          :max-count="1"
          :after-read="afterReadid"
        />
      </div>
      <div v-show="!pass" class="passreal">实名认证已通过</div>
      <div class="info">
        从业资格证<span>(协理/一般经纪人/高级经纪人)/选填</span>
      </div>
      <div class="picup">
        <van-uploader
          v-model="fileList1"
          max-count="1"
          accept="image/*"
          :after-read="afterRead1"
        />
      </div>
      <!-- <div class="info"><span class="haveto">*</span>在职证明</div>
      <div class="picup">
        <van-uploader
          max-count="1"
          accept="image/*"
          v-model="fileList2"
          :after-read="afterRead2"
        />
      </div>
      <div class="info"><span class="haveto">*</span>营业执照</div>
      <div class="picup">
        <van-uploader
          max-count="1"
          accept="image/*"
          v-model="fileList3"
          :after-read="afterRead3"
        />
      </div> -->
      <div class="info">
        <span style="color: red">*</span>工作照<span>(用于展示，一经审核通过无法修改)</span>
      </div>
      <div class="picup">
        <van-uploader
          v-model="fileList4"
          max-count="1"
          accept="image/*"
          :after-read="afterRead4"
        />
      </div>
      <div class="info"><span class="haveto">*</span>服务城市</div>
      <van-cell :title="area" size="large" is-link @click="showarea = true">{{
        value
      }}</van-cell>
      <div class="tipwords">
        <div>*身份证信息必须与从业资格证持证人信息一致</div>
        <div>*每日抢单任务根据主要服务区域优先匹配当地经纪人</div>
      </div>
      <div class="btnpart">
        <button @click="toon">现在加入 快速抢单赚佣金</button>
        <div class="safe" />
      </div>
    </div>

    <van-popup v-model="show" @close="onclose">
      <div class="showpart">
        <van-icon name="clock" size="50" color="#45b7cb" />
        <div class="onebox">请耐心等待</div>
        <div class="twobox">已提交验核</div>
      </div>
    </van-popup>
    <van-popup v-model="show2" @close="onclose2">
      <div class="showpart">
        <img class="unpass" src="../../assets/unpass.png" alt="" />
        <div class="onebox">
          <div class="threebox">身份信息验核不通过</div>
          <div class="threebox">请重新上传</div>
        </div>
        <button @click="show2 = false">重新上传</button>
      </div>
    </van-popup>
    <!-- <van-popup v-model="show3" @close="onclose3">
      <div class="showpart">
        <div class="onebox">
          <div class="threebox">恭喜!</div>
          <div class="threebox">您的经纪人身份已通过验核</div>
        </div>
        <img class="card" :src="agentReview.certificateUrl" alt="" />
        <div class="twobox">服务编号:{{ agent.agentSn }}</div>
        <button v-show="agent.vip != 2" @click="jumptojoin">加入会员</button>
      </div>
    </van-popup> -->
    <van-popup v-model="showarea" position="bottom" :style="{ height: '40%' }">
      <van-tree-select
        :items="items"
        :active-id.sync="activeId"
        :main-active-index.sync="activeIndex"
        @click-nav="getAdcode"
        @click-item="getCity"
      />
      <!-- <van-picker
        show-toolbar
        title="请选择期望的地点"
        :columns="columns"
        visible-item-count="4"
        @confirm="onConfirm"
        @cancel="onCancel"
      /> -->
    </van-popup>
  </div>
</template>

<script>
import { getToken } from "@/apis/house";
import {
  idcardUp,
  changerole,
  chaekCertification,
  applyDetail,
} from "../../apis/user.js";
import local from "../../utils/local.js";
import { dataURLtoFile, uuid } from "../../utils/help.js";
const qiniu = require("qiniu-js");
import { agenton } from "../../apis/buy.js";
import {
  getGeolocation,
  getChooseCity,
  setToken,
  setUserId,
  setRyToken,
} from "@/utils/auth";
import { mapGetters } from "vuex";
import { baseUtils } from "@/utils/baseUtils";
import { _local } from "@/utils/storage.js";
import { getAreaList } from "@/apis/city";

export default {
  data() {
    return {
      activeId: 0,
      activeIndex: 0,
      items: [
        {
          text: "区域",
          children: [],
          disabled: true,
        },
      ],
      adCode: "",
      city: "",
      cityList: [],
      fileListid: [],
      fileList1: [],
      fileList2: [],
      fileList3: [],
      fileList4: [],
      show: false,
      show2: false,
      show3: false,
      area: _local.get("city"),
      sendval: {
        certificateUrl: "",
        avatar: "",
        adcode: "",
        citycode: "",
        // businessLicenseUrl: "",
        // onJobCertificate: "",
      },
      token: "",
      flag: false,
      pass: true,
      showarea: false,
      arealist: [],
      columns: [],
      info: {},
      value: "",
      idcardUrl: "",
      uid: "",
      userId: "",
    };
  },
  computed: {
    ...mapGetters(["agent", "agentReview"]),
  },
  created() {
    changerole({ role: "4" }).then((res) => {
      console.log("切换经纪人身份", res);
      if (res.code == 200 || res.code == 201) {
        this.userId = res.result.userId;
        setUserId(res.result.userId);
        setToken(res.result.token);
        setRyToken(res.result.ryToken);
        this.uid = res.result.ryId;
        chaekCertification({ ryId: res.result.ryId }).then((res) => {
          console.log("用户信息", res);
          if (res.code == 200 || res.code == 201) {
            this.pass = false;
            this.flag = true;
            applyDetail({}).then((res) => {
              console.log("经纪人上传审核信息", res);
              if (res.code == 200 || res.code == 201) {
                this.sendval.certificateUrl = res.result.certificate_url;
                this.sendval.avatar = res.result.agent_avatar;
                const obj1 = { url: "", isImage: true };
                const obj2 = { url: "", isImage: true };
                obj1.url = res.result.certificate_url;
                obj2.url = res.result.agent_avatar;
                this.fileList1.push(obj1);
                this.fileList4.push(obj2);
              }
            });
          }
        });
      }
    });
    const chooseCity = getChooseCity();
    const geolocation = getGeolocation();
    if (!baseUtils.isEmpty(chooseCity)) {
      this.city = chooseCity.city;
    } else {
      this.city = geolocation.city;
    }

    console.log("rev length", this.agentReview);

    this.getqntoken();
    this.getInfo();
    if (!baseUtils.isEmpty(this.agent)) {
      // this.idcardUrl = this.agent.idcardUrl
      if (this.agent.idcardUrl) {
        const obj = { url: "", isImage: true };
        obj.url = this.$imgUrl + this.agent.idcardUrl;
        this.fileListid.push(obj);
        idcardUp({ idCardImage: this.agent.idcardUrl }).then((rep) => {
          if (rep.code === 2030 || rep.code === 2045) {
            this.$toast(rep.msg);
          } else if (rep.code === 200) {
            this.flag = true;
          }
        });
      }

      if (this.agent.area) {
        this.area = this.agent.area;
      }

      if (this.agent.area) {
        this.area = this.agent.area;
      }
      if (this.agent.adcode) {
        this.sendval.adcode = this.agent.adcode;
      }
      if (this.agent.certificateUrl) {
        this.sendval.certificateUrl = this.agent.certificateUrl;
        const obj = { url: "", isImage: true };
        obj.url = this.$imgUrl + this.agent.certificateUrl;
        this.fileList1.push(obj);
      }
      if (this.agent.avatar) {
        this.sendval.avatar = this.agent.avatar;
        const obj = { url: "", isImage: true };
        obj.url = this.$imgUrl + this.agent.avatar;
        this.fileList4.push(obj);
      }
    }
  },
  mounted() {
    this.getCityList();
    this.sendval.adcode = _local.get("adCode");
    this.sendval.citycode = _local.get("cityCode");
  },
  methods: {
    getCity(data) {
      this.showarea = false;
      this.value = data.text;
      this.area = data.text;
      this.sendval.adcode = data.adcode;
      this.sendval.citycode = data.citycode;
      // console.log(data)
    },
    getAdcode(index) {
      this.items[index].children = [];
      getAreaList({
        adcode: this.items[index].adcode,
      }).then((res) => {
        console.log(res);
        res.result.list.forEach((e, i) => {
          var obj = {};
          obj.text = e.name;
          obj.citycode = e.citycode;
          obj.adcode = e.adcode;
          obj.id = i;
          this.items[index].children.push(obj);
        });
      });
    },
    getCityList() {
      getAreaList().then((res) => {
        // console.log(res);
        res.result.list.forEach((e, i) => {
          // console.log(e)
          var obj = {};
          obj.text = e.name;
          obj.adcode = e.adcode;
          obj.children = [];
          this.items.push(obj);
        });
      });
    },
    back() {
      changerole({ role: _local.get("user").result.role }).then((res) => {
        console.log("切换原来身份", res);
        if (res.code == 200 || res.code == 201) {
          setUserId(res.result.userId);
          setToken(res.result.token);
          setRyToken(res.result.ryToken);
        }
      });
      this.$router.go(-1);
    },
    getInfo() {
      const user = _local.get("user").result;
      if (user.realNameAuthStatus === 1) {
        this.pass = false;
        this.flag = true;
      }
      if (user.agentReview.checkStatus === 1) {
        this.show = true;
      } else if (user.agentReview.checkStatus === 3) {
        this.show2 = true;
      } else if (user.agentReview.checkStatus === 2) {
        this.show3 = true;
      }
    },
    async toon() {
      if (this.flag) {
        if (this.sendval.adcode !== "") {
          this.sendval.uid = this.uid;
          await agenton(this.sendval).then((res) => {
            console.log(this.sendval);
            console.log(res);
            if (res.code === 200) {
              // this.show = true;
              this.$dialog
                .alert({
                  title: "温馨提示",
                  message: "提交审核成功，即将跳转到个人中心",
                  confirmButtonColor: "#45b7cb",
                  theme: "round-button",
                  messageAlign: "left",
                })
                .then(() => {
                  this.$router.push("/home/me");
                });
            } else if (res.code === 2052) {
              this.$toast(res.msg);
            }
          });
        } else {
          this.$toast("请填写服务城市");
        }
      } else {
        this.$toast("您还未通过实名验核");
      }
    },
    async getqntoken() {
      await getToken().then((res) => {
        local.set("qntoken", res.result.token);
        this.token = local.get("qntoken");
      });
    },
    onclose() {
      this.show = false;
    },
    onclose2() {
      this.show2 = false;
    },
    onclose3() {
      this.show3 = false;
    },
    onConfirm(value) {
      this.area = value;
      // this.value = "";
      this.arealist.forEach((e) => {
        if (e.name === value) {
          this.sendval.adcode = e.adcode;
          return;
        }
      });
      this.showarea = false;
    },
    onCancel() {
      this.showarea = false;
    },
    afterReadid(file) {
      const _this = this;
      const fileurl = file.content;
      const name = file.file.name;
      const imgfile = dataURLtoFile(fileurl, name);
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2,
        forceDirect: true,
      };
      const putExtra = {
        fname: name,
        mimeType: "image/jpeg;image/png",
      };
      const observer = {
        complete(res) {
          _this.idcardUrl = res.key;
          idcardUp({ idCardImage: res.key }).then((rep) => {
            console.log(rep);
            if (rep.code === 2030 || rep.code === 2045) {
              _this.$toast(rep.msg);
            } else if (rep.code === 200) {
              _this.flag = true;
            }
          });
        },
      };
      const observable = qiniu.upload(
        imgfile,
        "idcard/" + uuid(),
        this.token,
        putExtra,
        config
      );
      observable.subscribe(observer);
    },

    afterRead1(file) {
      const _this = this;
      const fileurl = file.content;
      const name = file.file.name;
      const imgfile = dataURLtoFile(fileurl, name);
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2,
        forceDirect: true,
      };
      const putExtra = {
        fname: name,
        mimeType: "image/jpeg;image/png",
      };
      const observer = {
        complete(res) {
          _this.sendval.certificateUrl = res.key;
        },
      };
      const observable = qiniu.upload(
        imgfile,
        "image/" + uuid(),
        this.token,
        putExtra,
        config
      );
      observable.subscribe(observer);
    },
    // afterRead2(file) {
    //   let _this = this;
    //   let fileurl = file.content;
    //   let name = file.file.name;
    //   let imgfile = dataURLtoFile(fileurl, name);
    //   const config = {
    //     useCdnDomain: true,
    //     region: qiniu.region.z2,
    //     forceDirect: true,
    //   };
    //   const putExtra = {
    //     fname: name,
    //     mimeType: "image/jpeg;image/png",
    //   };
    //   const observer = {
    //     complete(res) {
    //       _this.sendval.onJobCertificate = res.key;
    //     },
    //   };
    //   const observable = qiniu.upload(
    //     imgfile,
    //     "image/" + uuid(),
    //     this.token,
    //     putExtra,
    //     config
    //   );
    //   observable.subscribe(observer);
    // },
    // afterRead3(file) {
    //   let _this = this;
    //   let fileurl = file.content;
    //   let name = file.file.name;
    //   let imgfile = dataURLtoFile(fileurl, name);
    //   const config = {
    //     useCdnDomain: true,
    //     region: qiniu.region.z2,
    //     forceDirect: true,
    //   };
    //   const putExtra = {
    //     fname: name,
    //     mimeType: "image/jpeg;image/png",
    //   };
    //   const observer = {
    //     complete(res) {
    //       _this.sendval.businessLicenseUrl = res.key;
    //     },
    //   };
    //   const observable = qiniu.upload(
    //     imgfile,
    //     "image/" + uuid(),
    //     this.token,
    //     putExtra,
    //     config
    //   );
    //   observable.subscribe(observer);
    // },
    afterRead4(file) {
      const _this = this;
      const fileurl = file.content;
      const name = file.file.name;
      const imgfile = dataURLtoFile(fileurl, name);
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2,
        forceDirect: true,
      };
      const putExtra = {
        fname: name,
        mimeType: "image/jpeg;image/png",
      };
      const observer = {
        complete(res) {
          _this.sendval.avatar = res.key;
        },
      };
      const observable = qiniu.upload(
        imgfile,
        "agent/" + uuid(),
        this.token,
        putExtra,
        config
      );
      observable.subscribe(observer);
    },
    jumptojoin() {
      this.$router.push({ path: "/buyjoin" });
    },
  },
};
</script>

<style lang="less" scoped>
.info {
  margin: 10px 15px;
  font-size: 17px;
  font-weight: bold;

  span {
    font-size: 13px;
    color: #ccc;
    font-weight: normal;
  }
  .haveto {
    font-size: 20px;
    color: #d13531;
  }
}
.picup {
  margin: 0 15px;
}
.passreal {
  font-size: 13px;
  color: #45b7cb;
  margin: 0 25px 20px;
}
.tipwords {
  margin: 20px 30px;
  font-size: 12px;
  color: #999;
  padding-bottom: 100px;
  > div {
    margin-bottom: 7px;
  }
}
.btnpart {
  position: fixed;
  bottom: 0px;
  left: 0px;
  width: 100%;
  z-index: 100;
  padding: 15px 0 10px;
  border-top: 1px solid #f1f1f1;
  background-color: #fff;
  text-align: center;
  button:active {
    background-image: linear-gradient(to bottom right, #6fcddd75, #49b9cd79);
  }
  button {
    border: none;
    border-radius: 20px;
    height: 40px;
    width: 90%;
    color: #fff;
    background-image: linear-gradient(to bottom right, #6fccdd, #49b9cd);
  }
  .safe {
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
  }
}
.van-popup {
  border-radius: 15px;
}
.showpart {
  width: 300px;
  background-color: #fff;
  text-align: center;
  padding: 20px 0;
  border-radius: 15px;
  .card {
    height: 190px;
  }
  .unpass {
    width: 50px;
  }
  .onebox {
    color: #45b7cb;
    font-size: 17px;
    margin: 20px 0;
    font-weight: bold;
  }

  .twobox {
    font-size: 14px;
  }
  .threebox {
    color: #45b7cb;
    font-size: 17px;
    font-weight: bold;
  }
  button {
    background-color: #45b7cb;
    color: #fff;
    border: none;
    display: inline-block;
    border-radius: 15px;
    font-size: 14px;
    padding: 5px 15px;
    margin-top: 15px;
  }
}
</style>
